#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <fstream>
#include "imgUndistort.h"
#include <dirent.h>
using namespace cv;
using namespace std;

int getdir (std::string dir, std::vector<std::string> &files)
{
    DIR *dp;
    struct dirent *dirp;

    if((dp  = opendir(dir.c_str())) == NULL)
    {
        return -1;
    }

    while ((dirp = readdir(dp)) != NULL) {
     std::string name = std::string(dirp->d_name);

     if(name != "." && name != "..")
      files.push_back(name);
    }
    closedir(dp);

    std::sort(files.begin(), files.end());

    if(dir.at( dir.length() - 1 ) != '/') dir = dir+"/";
	for(unsigned int i=0;i<files.size();i++)
	{
		if(files[i].at(0) != '/')
		files[i] = dir + files[i];
	}

    return files.size();
}

int main()
{
	string datasetsPath="../img";//存放图片的路径
    vector<string> picName; 

	//获取所有图片的名字
	getdir(datasetsPath,picName);
	if(picName.size() == 0){
		cout<<"未获取到文件名！！！"<<endl;
		exit(0);
	}

	int image_count=0;  /* 图像数量 */
	for(int i=0;i<picName.size();i++)
	{
		image_count++;		
		// 用于观察检验输出
		std::cout<<"image_count = "<<image_count<<endl;		
		cv::Mat imgInput=imread(picName[i]);
		
		cv::Mat imgOutput=imgInput.clone();

		if(imgInput.empty())
			return 0;

		// 去畸变
		imgUndistort(imgInput,imgOutput);
		//bzero(filename);
		//sprintf(filename, "../img/%d_undistort.jpg", image_count);
		string filename = "../img/"+to_string(image_count)+"_undistort.jpg";
		cv::imwrite(filename, imgOutput);
		cv::imshow("Camera Calibration",imgOutput);//显示图片
		waitKey(5);//暂停0.5S		
	}
	/*	
	std::string imgName = "../img/1.jpg";
	cv::Mat imgInput=cv::imread(imgName);
	cv::Mat imgOutput=imgInput.clone();

	if(imgInput.empty())
		return 0;

	// 去畸变
	imgUndistort(imgInput,imgOutput);

	// 结果显示
	cv::imshow("原始图像",imgInput);
	cv::imshow("去畸变图像",imgOutput);
	cv::waitKey(0);
	*/
	return 0;
}
